<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) wangyt <wangtom365@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Http\Controllers\Admins;

use App\Models\Books\BookSectionsModel;
use App\Models\Books\BooksModel;
use App\Models\Books\BookTextsModel;
use Illuminate\Http\Request;

class BookController extends AdminController
{
    /**
     * 列表.
     *
     * @return string
     */
    public function index(Request $request)
    {
        return $this->list($request);
    }

    public function sectionList(Request $request, $bookId = 0)
    {
        $page = $request->input('page', 0);
        $category = $request->input('category', '');
        $data = [];
        $where = [];
        if ($bookId) {
            $where['book_id'] = $bookId;
        }
// var_dump($bookId);exit;
        $data['detailInfo'] = (new BooksModel())->findOrFail($bookId)->toArray();

        $result = (new BookSectionsModel())->getListWithPaginate($where, $page);
        // print_r($result);exit;
        if (empty($result)) {
            return '没有获取到数据.请确认URL是否正确.';
        }
        // $data['categoryList'] = (new BookSectionsModel())->getList();
        // $data['categoryCount'] = (new PostModel())->getListGroupByCategory();

        $data['listData'] = $result;
// print_r($data);exit;

        return view('admins.books.bookSectionList', $data);
    }

    /**
     * 章节添加.
     *
     * @param Request $request
     * @param int     $bookId
     */
    public function sectionAdd(Request $request, $bookId = 0)
    {
        $data = [];
        $data['detail'] = $this->getBookInfo($bookId);
// print_r($data);exit;

        if ($request->input('_token') !== null) {
            // 添加文本内容
            $editorValue = $request->get('editorValue', '');
            $input = [
                'book_id' => $bookId,
                'content' => $editorValue,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $textId = (new BookTextsModel())->saveData(collect($input));

            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];

            // 添加章节信息
            $input = [
                'book_id' => $bookId,
                'text_id' => $textId,
                'title' => $request->get('title', ''),
                'remark' => $request->get('remark', ''),
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $sectionId = (new BookSectionsModel())->saveData(collect($input));

            if ($sectionId) {
                $response['code'] = 1;
                $response['data'] = [
                    'id' => $sectionId,
                    'url' => route('section-edit', [
                        'bid' => $bookId,
                        'id' => $sectionId,
                    ]),
                ];
            }
        // print_r($input);
            return response($response, 200);
        }
        $data['configs'] = $this->getYamlContent(config_path('admins/books.yaml'));
// print_r($booksConfig);
        // $data['categoryList'] = (new CategoryModel())->getList();
        // $data['parentCategoryList'] = (new CategoryModel)->getParentCategoryList();
        $data['options'] = [];
        // $data['options']['parent_id'] = collect($data['parentCategoryList'])->mapWithKeys(function($item){
        //     // print_r($item);
        //     return [$item['category_id'] => $item['category_name']];
        // });

        return view('admins.books.bookSectionAdd', $data);
    }

    /**
     * 获取图书详情.
     *
     * @param int $bookId
     * @param int $sectionId
     */
    public function getBookInfo($bookId = 0, $sectionId = 0)
    {
        $data = [
            'bookInfo' => [],
            'sectionList' => [],
            'sectionInfo' => [],
            'textInfo' => [],
        ];
        // 图书信息
        $data['bookInfo'] = (new BooksModel())->findOrFail($bookId)->toArray();

        // 章节信息
        $where = [
            'book_id' => $bookId,
        ];
        $data['sectionList'] = (new BookSectionsModel())->getList($where);

        if ($sectionId) {
            // 当前章节
            $data['sectionInfo'] = collect($data['sectionList'])->where('id', $sectionId)->first();

            // 章节详情
            $textId = $data['sectionInfo']['text_id'];
            $data['textInfo'] = (new BookTextsModel())->find($textId)->toArray();
        }

        return $data;
    }

    /**
     * 章节编辑.
     *
     * @param Request $request
     * @param int     $id
     * @param mixed   $bookId
     * @param mixed   $sectionId
     */
    public function sectionEdit(Request $request, $bookId = 0, $sectionId = 0)
    {
        $data = [];
        // 图书信息
        $data['detail'] = $this->getBookInfo($bookId, $sectionId);
// print_r($data);exit;
        if ($request->input('_token') !== null) {
            // 添加文本内容
            $editorValue = $request->get('editorValue', '');
            $input = [
                'book_id' => $bookId,
                'content' => $editorValue,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $textId = (new BookTextsModel())->saveData(collect($input));

            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];

            // 添加章节信息
            $where = ['id' => $sectionId];
            $input = [
                'text_id' => $textId,
                'title' => $request->get('title', ''),
                'remark' => $request->get('remark', ''),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            $result = (new BookSectionsModel())->updateData(['id' => $sectionId], $input);

            if ($result) {
                $response['code'] = 1;
                $response['data'] = [
                    'id' => $sectionId,
                    'url' => route('section-edit', [
                        'bid' => $bookId,
                        'id' => $sectionId,
                    ]),
                ];
            }
        // print_r($input);
            return response($response, 200);
        }

        // $data['categoryList'] = (new PostCategoryModel())->getList();
        $data['configs'] = $this->getYamlContent(config_path('admins/books.yaml'));

        return view('admins.books.bookSectionEdit', $data);
    }

    public function list(Request $request)
    {
        $page = $request->input('page', 0);
        $category = $request->input('category', '');
        $data = [];
        $where = [];
        if ($category) {
            $where['category'] = $category;
        }

        $result = (new BooksModel())->getListWithPaginate($where, '*', $limit = 10);
        if (empty($result)) {
            return '没有获取到数据.请确认URL是否正确.';
        }
        // $data['categoryList'] = (new BookSectionsModel())->getList();
        // $data['categoryCount'] = (new PostModel())->getListGroupByCategory();

        $data['listData'] = $result;
// print_r($data);exit;

        return view('admins.books.bookList', $data);
    }

    /**
     * 添加.
     *
     * @param Request $request
     */
    public function add(Request $request)
    {
        if ($request->input('_submit') !== null) {
            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];
            $input = [];
            $input['platform'] = 'posts';
            $input['category'] = $request->input('category', '');

            $input['book_name'] = $request->input('book_name');
            $input['book_name_en'] = $request->input('book_name_en');
            $input['book_description'] = $request->input('book_description');
            $input['remark'] = $request->input('remark');
            $input['created_at'] = date('Y-m-d H:i:s');
            // $input['updated_at']  = date('Y-m-d H:i:s');

            $result = (new BooksModel())->saveData(collect($input));

            if ($result) {
                $response['code'] = 1;
                $response['data'] = [
                    'id' => $result,
                    'url' => '/admins/books/edit/'.$result,
                ];
            }
        // print_r($input);
            return response($response, 200);
        }
        $data = [];
        $data['configs'] = $this->getYamlContent(config_path('admins/books.yaml'));
// print_r($booksConfig);
        // $data['categoryList'] = (new CategoryModel())->getList();
        // $data['parentCategoryList'] = (new CategoryModel)->getParentCategoryList();
        $data['options'] = [];
        // $data['options']['parent_id'] = collect($data['parentCategoryList'])->mapWithKeys(function($item){
        //     // print_r($item);
        //     return [$item['category_id'] => $item['category_name']];
        // });

        return view('admins.books.bookAdd', $data);
    }

    /**
     * 编辑.
     *
     * @param Request $request
     * @param int     $bookId
     */
    public function edit(Request $request, $bookId = 0)
    {
        if ($request->input('_submit') !== null) {
            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];
            $input = [];
            $input = [];
            $input['platform'] = 'posts';
            $input['category'] = $request->input('category', '');

            $input['book_name'] = $request->input('book_name');
            $input['book_name_en'] = $request->input('book_name_en');
            $input['book_description'] = $request->input('book_description');
            $input['remark'] = $request->input('remark');
            $input['created_at'] = date('Y-m-d H:i:s');
            // $input['updated_at']  = date('Y-m-d H:i:s');
            $input['updated_at'] = date('Y-m-d H:i:s');

            $where = [
                'id' => $bookId,
            ];
            $result = (new BooksModel())->updateData($where, $input);
            if ($result) {
                $response['code'] = 1;
                $response['data'] = [
                    'id' => $bookId,
                    'url' => '/admins/books/edit/'.$bookId,
                ];
            }
        // print_r($input);
            return response($response, 200);
        }

        $result = (new BooksModel())->findOrFail($bookId);

        // $data['categoryList'] = (new PostCategoryModel())->getList();
        $data['configs'] = $this->getYamlContent(config_path('admins/books.yaml'));

        $data['detail'] = $result->toArray();

        return view('admins.books.bookEdit', $data);
    }

    public function ajax(Request $request)
    {
        $action = $request->get('action');
        if ($action === 'updateStatus') {
            $bookId = $request->get('id', 0);
            $where = [
                'id' => $bookId,
                'status' => $request->get('currentStatus', -1),
            ];
            $update = [
                'status' => $request->get('targetStatus', -1),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            $result = (new BooksModel())->updateData($where, $update);
            if ($result) {
                self::renderApiSuccess('success', ['bookId' => $bookId]);
            }
        }

        self::renderApiSuccess('success', $request->all());
    }
}
